package cn.operation.backend.service.baseSeries;


import cn.operation.backend.bo.CvSeriesBO;
import cn.operation.backend.bo.baseBrand.SeriesQueryBo;
import cn.operation.backend.enums.BaseStatusEnum;
import cn.operation.backend.query.SeriesQueryConditions;
import cn.operation.backend.service.baseBrand.ScBaseCvBrandService;
import cn.operation.backend.util.BusinessException;
import cn.operation.backend.util.PageVo;
import cn.operation.backend.util.ResultDTOWithPagination;
import cn.operation.base.mapper.ScBaseCvBrandMapper;
import cn.operation.base.mapper.ScBaseCvSeriesMapper;
import cn.operation.base.mapper.extmapper.baseBrand.ScBaseSeriesExpandMapper;
import cn.operation.base.model.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName:
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 下午4:04
 */
@Service
public class SeriesServiceImpl implements SeriesService {

	@Autowired
	private ScBaseCvSeriesMapper scBaseCvSeriesMapper;

	@Autowired
	private ScBaseCvBrandMapper scBaseCvBrandMapper;

	@Autowired
	ScBaseSeriesExpandMapper scBaseSeriesExpandMapper;
	
	@Autowired
	ScBaseCvBrandService scBaseCvBrandService;

	private static final Logger LOGGER = LoggerFactory.getLogger(SeriesServiceImpl.class);

	public void verificationForm(BindingResult br) {

		if (null == br) {
			LOGGER.error("SeriesServiceImpl.verificationForm error br is null");
			throw new IllegalArgumentException("BindingResult is null");
		}

		if (br.hasErrors()) {
			List<ObjectError> list = br.getAllErrors();
			LOGGER.error("DRouteServiceImpl.add error : {}", list.get(0).getDefaultMessage());
			throw new IllegalArgumentException(list.get(0).getDefaultMessage());
		}
	}

	@Override
	public ResultDTOWithPagination<Object> selectListByConditions(PageVo pageVo, SeriesQueryConditions conditions)
			throws Exception {
		LOGGER.info("SeriesServiceImpl.selectListByConditions params : {}, {}", pageVo, conditions);

		if (null == conditions) {
			LOGGER.error("SeriesServiceImpl.selectListByConditions param conditions must not be null ");
			throw new IllegalArgumentException("条件不能为空");
		}

		String orderByClause = null;
		if (null != pageVo) {
			orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
		}

		ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
		ScBaseCvSeriesExample.Criteria criteria = example.createCriteria();

		if (StringUtils.isNotBlank(conditions.getName())) {
			criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
		}
		if (conditions.getBrandId() != null && conditions.getBrandId() > 0) {
			criteria.andBrandIdEqualTo(conditions.getBrandId());
		}
		criteria.andStatusNotEqualTo(BaseStatusEnum.DELETE.getValue());

		if (null != pageVo) {
			pageVo.setTotalRecord(scBaseCvSeriesMapper.countByExample(example));
			example.setLimitStart(pageVo.getStartIndex());
			example.setLimitEnd(pageVo.getPageSize());
			example.setOrderByClause(orderByClause);
		}

		List<ScBaseCvSeries> list = scBaseCvSeriesMapper.selectByExample(example);

		List<CvSeriesBO> listBO = new ArrayList<>();

		for (ScBaseCvSeries scBaseCvSeriesAndBrand : list) {
			ScBaseCvBrand scBaseCvBrand = scBaseCvBrandMapper.selectByPrimaryKey(scBaseCvSeriesAndBrand.getBrandId());
			CvSeriesBO bo = new CvSeriesBO();
			BeanUtils.copyProperties(scBaseCvSeriesAndBrand, bo);
			if (scBaseCvBrand != null)
				bo.setBrandName(scBaseCvBrand.getName());
			listBO.add(bo);
		}
		ResultDTOWithPagination<Object> result = new ResultDTOWithPagination<>(true, null, "查询成功");
		result.setData(listBO);

		if (null != pageVo) {
			result.setPageVo(pageVo);
		}

		return result;
	}

	@Override
	public Integer addSeries(CvSeriesBO form, BindingResult br) throws Exception {
		LOGGER.info("SeriesServiceImpl.add params : {}", form);

		if (null == form) {
			LOGGER.error("SeriesServiceImpl.add param form must not be null ");
			throw new IllegalArgumentException("数据不能为空");
		}

		// 验证表单
		verificationForm(br); // 改在Controller验证

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationSeriesCodeUnique(form);

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationSeriesNameUnique(form);

		ScBaseCvSeries scBaseCvSeries = new ScBaseCvSeries();
		BeanUtils.copyProperties(form, scBaseCvSeries);

		scBaseCvSeriesMapper.insertSelective(scBaseCvSeries);

		return scBaseCvSeries.getId();
	}

	public void verificationSeriesCodeUnique(CvSeriesBO form) throws Exception {
		LOGGER.info("SeriesServiceImpl.verificationSeriesCodeUnique params : {}, {}", form);

		if (form.getCode() == null) {
			LOGGER.error("SeriesServiceImpl.verificationSeriesCodeUnique param form must not be null");
			throw new IllegalArgumentException("品牌编码不能为空");
		}

		ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
		example.createCriteria().andCodeEqualTo(form.getCode());
		example.createCriteria().andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
		List<ScBaseCvSeries> list = scBaseCvSeriesMapper.selectByExample(example);

		if (list!=null&&list.size()>0) {

			ScBaseCvSeries scBaseCvSeries = list.get(0);

			// 修改时判断 如果id一致则修改时未改变
			if (form.getId() != null && form.getId().equals(scBaseCvSeries.getId())) {
				return;
			}
			LOGGER.error("SeriesServiceImpl.verificationSeriesCodeUnique error list is not empty");
			throw new BusinessException("车系编码已存在！");
		}
	}

	public void verificationSeriesNameUnique(CvSeriesBO form) throws Exception {
		LOGGER.info("SeriesServiceImpl.verificationSeriesNameUnique params : {}, {}", form);

		if (form.getName() == null) {
			LOGGER.error("SeriesServiceImpl.verificationSeriesNameUnique param form must not be null");
			throw new IllegalArgumentException("品牌名称不能为空");
		}

		ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
		example.createCriteria().andNameEqualTo(form.getName());
		example.createCriteria().andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
		List<ScBaseCvSeries> list = scBaseCvSeriesMapper.selectByExample(example);

		if (list!=null&&list.size()>0) {

			ScBaseCvSeries scBaseCvSeries = list.get(0);

			// 修改时判断 如果id一致则修改时未改变
			if (form.getId() != null && form.getId().equals(scBaseCvSeries.getId())) {
				return;
			}
			LOGGER.error("SeriesServiceImpl.verificationSeriesNameUnique error list is not empty");
			throw new BusinessException("车系名称已存在！");
		}

	}

	@Override
	public ScBaseCvSeries selectSeriesById(Integer id) {
		LOGGER.info("SeriesServiceImpl.selectSeriesById param : {}", id);

		if (id == null) {
			LOGGER.error("SeriesServiceImpl.selectSeriesById param Code must not be null ");
			throw new IllegalArgumentException("ID不能为空");
		}
		return scBaseCvSeriesMapper.selectByPrimaryKey(id);
	}

	@Override
	public Integer seriesUpdate(CvSeriesBO form, BindingResult br) throws Exception {
		LOGGER.info("SeriesServiceImpl.seriesUpdate params : {}", form);
		if (null == form) {
			LOGGER.error("SeriesServiceImpl.seriesUpdate param form must not be null ");
			throw new IllegalArgumentException("不能为空");
		}

		// 验证表单
		verificationForm(br); // 改在Controller验证

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationSeriesCodeUnique(form);

		// 业务验证 验证状态为正常的编码是否唯一
		this.verificationSeriesNameUnique(form);

		ScBaseCvSeries scBaseCvSeries = new ScBaseCvSeries();
		BeanUtils.copyProperties(form, scBaseCvSeries);

		scBaseCvSeriesMapper.updateByPrimaryKeySelective(scBaseCvSeries);

		return scBaseCvSeries.getId();
	}

	@Override
	public int deleteSeriesBatch(List ids) throws Exception {
		LOGGER.info("SeriesServiceImpl.updateCodeGroup params : {}", ids);
		if (null == ids || ids.size() < 1) {
			LOGGER.error("SeriesServiceImpl.deleteCodeGroupBatch param form must not be null ");
			throw new IllegalArgumentException("数据不能为空");
		}
		return scBaseCvSeriesMapper.batchDelete(ids);
	}

	@Override
	public List<ScBaseCvSeries> getAllList(PageVo pageVo, SeriesQueryConditions conditions) {
		LOGGER.info("SeriesServiceImpl.getAllList params : {}, {}", pageVo, conditions);

		if (null == conditions) {
			LOGGER.error("SeriesServiceImpl.getAllList param conditions must not be null ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}

		String orderByClause = null;
		if (null != pageVo) {
			orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
		}

		ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
		ScBaseCvSeriesExample.Criteria criteria = example.createCriteria();

		if (conditions.getBrandId() != null && conditions.getBrandId() > 0) {
			criteria.andBrandIdEqualTo(conditions.getBrandId());
		}
		if (StringUtils.isNotBlank(conditions.getName())) {
			criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
		}
		criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());

		if (null != pageVo) {
			pageVo.setTotalRecord(scBaseCvSeriesMapper.countByExample(example));
			example.setLimitStart(pageVo.getStartIndex());
			example.setLimitEnd(pageVo.getPageSize());
			example.setOrderByClause(orderByClause);
		}

		List<ScBaseCvSeries> list = scBaseCvSeriesMapper.selectByExample(example);

		return list;
	}

	@Override
	public List<ScBaseCvSeries> selectAllSeries() throws Exception {
		ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
		ScBaseCvSeriesExample.Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
		return scBaseCvSeriesMapper.selectByExample(example);
	}

	@Override
	public Integer selectCountList(SeriesQueryConditions conditions) {
		LOGGER.info("SeriesServiceImpl.selectCountList params : {}, {}", conditions);

		if (null == conditions) {
			LOGGER.error("SeriesServiceImpl.selectCountList param conditions must not be null ");
			throw new IllegalArgumentException("查询条件信息不能为空");
		}

		ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
		ScBaseCvSeriesExample.Criteria criteria = example.createCriteria();

		if (conditions.getBrandId() != null && conditions.getBrandId() > 0) {
			criteria.andBrandIdEqualTo(conditions.getBrandId());
		}
		if (StringUtils.isNotBlank(conditions.getName())) {
			criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
		}
		criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());

		return scBaseCvSeriesMapper.countByExample(example);
	}


	@Override
	public List<ScBaseCvSeries> getByCondition(PageVo pageVo, SeriesQueryBo conditions) throws Exception {
		LOGGER.info("SeriesServiceImpl.getByCondition params : {}, {}", pageVo, conditions);
		try {

			String orderByClause = null;

			if (null != pageVo) {
				orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
			}

			ScBaseCvSeriesExample example = new ScBaseCvSeriesExample();
			ScBaseCvSeriesExample.Criteria criteria = example.createCriteria();

			if (null != conditions && null != conditions.getId() && conditions.getId() > 0) {
				criteria.andBrandIdEqualTo(conditions.getId());
			}


			if (null != conditions && StringUtils.isNotBlank(conditions.getCode())) {
				criteria.andCodeEqualTo(conditions.getCode());
			}
			
			if (null != conditions && StringUtils.isNotBlank(conditions.getName())) {
				criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
			}

			criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());

			if (null != pageVo) {
				pageVo.setTotalRecord(scBaseCvSeriesMapper.countByExample(example));
				example.setLimitStart(pageVo.getStartIndex());
				example.setLimitEnd(pageVo.getPageSize());
				example.setOrderByClause(orderByClause);
			}

			List<ScBaseCvSeries> list = scBaseCvSeriesMapper.selectByExample(example);

			return list;
		} catch (Exception e) {
			LOGGER.error("eriesServiceImpl.getByCondition error :", e);
			throw new BusinessException("查询车系异常");
		}
	}
}
